<div>
  <div id="title">
    <button data-path="/home">首页</button>
    <button data-path="/center">我的</button>
    <button data-path="/hot">热门</button>
  </div>
  <div id="view"></div>
</div>

<script>
  const oBtns = document.querySelectorAll('#title>button');
  const oView = document.getElementById('view');
  // 路由表
  const routes = [
    { path: '/home', component: '欢迎来到首页' },
    { path: '/center', component: '我真的不是大冤种' },
    { path: '/hot', component: '武汉尚硅谷XXX拿到30k offer' },
  ];

  //给所有的button绑定点击事件
  for (var i = 0; i < oBtns.length; i++) {
    oBtns[i].onclick = function () {
      // 调用history对象的pushState方法来添加一个state (路由路径)    replaceState
      history.pushState(null, null, this.dataset.path);

      // 得到手动遍历查找对应的路由组件去更新显示
      routes.forEach((route) => {
        if (route.path === this.dataset.path) {
          oView.innerHTML = route.component;
        }
      });
    };
  }

  // 监视浏览器的前进和回退的, 不能监视pushState导致的变化
  window.onpopstate = function () {
    console.log(location.pathname);
    routes.forEach((route) => {
      if (route.path === location.pathname) {
        oView.innerHTML = route.component;
      }
    });
  };
</script>
